package com.xxd.gulimail.product.service.impl;

import com.xxd.common.to.SkuReductionTo;
import com.xxd.common.to.SpuBoundsTo;
import com.xxd.common.utils.R;
import com.xxd.gulimail.product.entity.*;
import com.xxd.gulimail.product.feign.CouponFeignService;
import com.xxd.gulimail.product.service.*;
import com.xxd.gulimail.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxd.common.utils.PageUtils;
import com.xxd.common.utils.Query;

import com.xxd.gulimail.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    SpuInfoDescService spuInfoDescService;
    @Resource
    SpuImagesService spuImagesService;
    @Resource
    SkuImagesService skuImagesService;
    @Resource
    ProductAttrValueService productAttrValueService;
    @Resource
    AttrService attrService;
    @Resource
    SkuInfoService skuInfoService;
    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {
        //1.保存spu基本信息
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        //2.保存spu的描述图片
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        if (decript.size() > 0){descEntity.setDecript(String.join(",",decript));}
        spuInfoDescService.save(descEntity);
        //3.保存spu的图片集
        List<String> images = spuInfo.getImages();
        spuImagesService.saveImages(images,infoEntity.getId());
        //4.保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        //4.1优化循环查库
        List<Long> attrids = baseAttrs.stream().map(obj -> obj.getAttrId()).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = attrService.listByIds(attrids);
        Map<Long, String> map = new HashMap<Long, String>();
        if( attrEntities!=null ){
            for (AttrEntity attrEntity : attrEntities) {
                map.put(attrEntity.getAttrId(),attrEntity.getAttrName());
            }
        }
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(obj -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            entity.setAttrId(obj.getAttrId());
            entity.setAttrName(map.get(obj.getAttrId()));
            entity.setAttrValue(obj.getAttrValues());
            entity.setQuickShow(obj.getShowDesc());
            entity.setSpuId(infoEntity.getId());
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

        //5.保存spu的积分信息（跨库）
        Bounds bounds = spuInfo.getBounds();
        SpuBoundsTo boundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,boundsTo);
        boundsTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(boundsTo);
        if (r.getCode()!=0){
            log.error("远程保存spu的积分信息失败！");
        }
        //5.保存当前spu对应的sku信息
        //5.1 sku的基本信息，
        List<Skus> skus = spuInfo.getSkus();
        if (skus!=null){
            for (Skus sku : skus) {
                String defaultImg = "";
                if (sku.getImages()!=null){
                    for (Image image : sku.getImages()) {
                        if (image.getDefaultImg()==1){
                            defaultImg = image.getImgUrl();
                        }
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(obj -> {
                    SkuImagesEntity entity = new SkuImagesEntity();
                    entity.setSkuId(skuId);
                    entity.setImgUrl(obj.getImgUrl());
                    entity.setDefaultImg(obj.getDefaultImg());
                    return entity;
                }).filter(entity->{
                    //返回true就是需要，false就会被过滤
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2 保存sku的图片信息 //TODO 没有图片路径的无需保存
                skuImagesService.saveBatch(skuImagesEntities);
                //5.3 sku的销售属性基本信息，
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> attrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueEntities);
                //5.4 sku的优惠满减等信息，sms_会员表，跨库
                SkuReductionTo reductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,reductionTo);
                reductionTo.setSkuId(skuId);
                if (reductionTo.getFullCount() > 0 || reductionTo.getFullPrice().compareTo(new BigDecimal(0))==1){
                    R r1 = couponFeignService.saveSkuReduction(reductionTo);
                    if (r1.getCode()!=0){
                        log.error("保存sku的优惠满减等信息失败");
                    }
                }
            }
        }




    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    //根据条件查询
    /*t:
    1666091664528
    status:
    key:
    brandId:
    catelogId:
    page:
    limit:
    */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(obj->{
                obj.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && Integer.parseInt(brandId) > 0 ){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && Integer.parseInt(catelogId) > 0){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
               wrapper
        );
        return new PageUtils(page);
    }

}